<?php


namespace app\index\controller;


use app\admin\service\RbacService;
use app\common\exception\ParameterFailedException;
use app\common\service\Lang;
use app\common\service\Qiniu;
use think\facade\Db;

class MediaController
{
    public function uploadImage()
    {
        Db::startTrans();
        try {

            //            $params      = self::getParam(['type']);
            //            (new MediaValidate())->goCheck(__FUNCTION__, $params);
            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('file');
            if (!$file) {
                throw new ParameterFailedException();
            }
            //                halt($files[0]->getOriginalName());die;
            // 移动到框架应用根目录/uploads/ 目录下
            switch (config('filesystem.default')) {
                //                case 'local':
                //                    $path = config('filesystem.disks.local.root');
                //                    break;
                //                case 'public';
                //                    $path = config('filesystem.disks.public.root');
                //                    break;
                case 'qiniuyun';
                    $path = config('filesystem.disks.qiniuyun.root');
                    break;
                default:
                    throw new ParameterFailedException(['msg' => '只支持七牛云']);
            }
            //            $saveFileInfo = [];
            $temp         = \think\facade\Filesystem::putFile('', $file);
            $filesavepath = $path . DIRECTORY_SEPARATOR . $temp;
            //            $saveFileInfo[] = [
            //                'savename'      => $temp,
            //                'filename'      => $files[0]->getOriginalName(),
            //                'complete_file' => $path . DIRECTORY_SEPARATOR . $temp,
            //            ];
            $filename = getUniqueStr().$file->getOriginalName();
            (new Qiniu())->uploadFile($filesavepath, $filename);

            Db::commit();
            unlink($filesavepath);
            return retJson(Lang::UPLOADDone, ['url' => 'https://file.uziyuan.vip/' . $filename]);
        } catch (\Exception $e) {
            if (isset($filesavepath)) {
                unlink($filesavepath);
            }
            // 回滚事务
            Db::rollback();
            throw new ParameterFailedException(['msg' => $e->getMessage()]);
        }
    }
}